package com.changli03.threadsafe.threadsafe;

public class WindowTest {
    public static void main(String[] args) {
        Window w1 = new Window();
        Window w2 = new Window();
        Window w3 = new Window();
        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");
        w1.start();
        w2.start();
        w3.start();
    }
}
class Window extends Thread {
    static int ticket = 100;
    static Object lock = new Object();
    @Override
    public void run() {
        while (true) {
//            synchronized (this) { // this 不唯一 w1,w2,w3 各自对应了各自的this
//            synchronized (lock) {// obj 用static 修饰之后 是唯一的
            synchronized (Window.class) {// Class cls = Window.class
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "票号为:" + ticket);
                    ticket--;
                }
                else{
                    break;
                }
            }
        }
    }
}
